define(function(require) {
    "use strict";
    var ko = require("knockout");
    var router = require("plugins/router");
    var layui = require("layui");
    var $ = require("jquery");
    var system = require("durandal/system");
    var shareUrlContent = require("text!./share-url-content.html");

    var dateFtt = function(fmt, date) { //author: meizz
        var o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours() % 12 == 0 ? 12 : date.getHours() % 12, //小时
            "H+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        if(/(y+)/.test(fmt))
            fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
        for(var k in o)
            if(new RegExp("("+ k +")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
        return fmt;
    };

    var acceptPageSize = [10, 30, 60, 90, 150, 300];
    var param = {
        wildcardKeyword: ko.observable(""),
        termKeyword: ko.observable(""),
        termKeywordOr: ko.observable(""),
        searchDate: ko.observable(""),
        actionId: ko.observable(""),
        curr: 1,
        limit: acceptPageSize[0]
        //page: 1
    };

    var tableIns = null;

    var modelId = null;
    var currentAction = ko.observable(null);
    var pageList = ko.observableArray([]);

    var requestData = function() {
        if (param.wildcardKeyword() || param.termKeyword() || param.termKeywordOr()) {
            $.ajax({
                type: "GET",
                url: "/back/sourceKeyword",
                dataType: "json",
                contentType: "application/json",
                data: {
                    wildcardKeyword: param.wildcardKeyword(),
                    termKeyword: param.termKeyword(),
                    termKeywordOr: param.termKeywordOr(),
                    actionId: currentAction() ? currentAction().id : "",
                    planId: modelId,
                    page: param.curr,
                    limit: param.limit
                }
            }).then(function(data) {

                layui.use("laypage", function() {
                    var laypage = layui.laypage;

                    //执行一个laypage实例
                    laypage.render({
                        elem: "keyword-page", //注意，这里的 test1 是 ID，不用加 # 号
                        count: data.count, //数据总数，从服务端得到
                        curr: param.curr,
                        layout: ["count", "prev", "page", "next", "limit", "skip"],
                        jump: function(obj, first) {
                            param.curr = obj.curr;
                            param.limit = obj.limit;
                            //首次不执行
                            if (!first) {
                                requestData();
                            }
                        }
                    });
                });

                pageList(data.data);
            }, function(data) {
                layui.use("layer", function() {
                    var layer = layui.layer;
                    layer.alert(data.msg);
                });
            });
        } else {
            pageList([]);
        }
    };

    return {
        activate: function(id, queryParam) {
            //重置部分参数防止缓存
            param.actionId("");
            param.searchDate("");

            modelId = id;
            if (!((typeof queryParam === "object") && queryParam)) {
                queryParam = { };
            }
            if ((typeof queryParam.actionId === "string") && queryParam.actionId) {
                param.actionId(queryParam.actionId);
            } else {
                if ((typeof queryParam.searchDate === "string") && queryParam.searchDate) {
                    param.searchDate(queryParam.searchDate);
                } else {
                    param.searchDate(dateFtt("yyyy-MM-dd HH:mm:ss", new Date()));
                }
            }
            if ((typeof queryParam.term === "string") && queryParam.term) {
                param.termKeyword(queryParam.term);
            } else {
                param.termKeyword("");
            }
            if ((typeof queryParam.termKeywordOr === "string") && queryParam.termKeywordOr) {
                param.termKeywordOr(queryParam.termKeywordOr);
            } else {
                param.termKeywordOr("");
            }
            if ((typeof queryParam.wildcard === "string") && queryParam.wildcard) {
                param.wildcardKeyword(queryParam.wildcard);
            } else {
                param.wildcardKeyword("");
            }

            var promise = null;
            if (param.actionId()) {
                promise = $.ajax({
                    type: "get",
                    url: "/back/actionById/" + param.actionId(),
                    dataType: "json"
                }).then(function(response) {
                    currentAction(response.data);
                }, function(data) {
                    layui.use(["layer"], function() {
                        var layer = layui.layer;
                        layer.alert(data.responseJSON.msg);
                    });
                });
            } else {
                promise = $.ajax({
                    type: "get",
                    url: "/back/actionByTime",
                    dataType: "json",
                    data: { time: encodeURIComponent(param.searchDate()), planId: modelId }
                }).then(function(response) {
                    currentAction(response.data);
                }, function(data) {
                    layui.use(["layer"], function() {
                        var layer = layui.layer;
                        layer.alert(data.responseJSON.msg);
                    });
                });
            }
            promise.then(function() {
                return requestData();
            });
            return promise;
        },
        param: param,
        currentAction: currentAction,
        pageList: pageList,
        compositionComplete: function() {
            layui.use(["laytpl", "table", "element", "layer", "laydate", "form"], function() {
                var laytpl = layui.laytpl;
                var table = layui.table;
                var element = layui.element;
                var layer = layui.layer;
                var laydate = layui.laydate;
                var form = layui.form;

                $("#share-url").click(function() {
                    var url = "http://" + window.location.host + "/kunlunAssets/index.html#plan/sourceKeyword/" + modelId + "?term=" + encodeURIComponent(param.termKeyword()) + "&termKeywordOr=" + encodeURIComponent(param.termKeywordOr()) + "&wildcard=" + encodeURIComponent(param.wildcardKeyword()) + "&searchDate=" + encodeURIComponent(param.searchDate()) + "&actionId=" + encodeURIComponent(param.actionId());
                    layer.open({
                        content: shareUrlContent,
                        shadeClose: true,
                        btn: [],
                        title: "请复制",
                        success: function(layero, index) {
                            var inputDom = $(layero.selector).find(".share-url-input");
                            inputDom.val(url);
                            inputDom.select();
                        }
                    });
                    return false;
                });

                form.on("submit(search-submit)", function(data) {
                    param.curr = 1;
                    requestData();
                    return false;
                });
            });
        }
    };
});